<script setup>
import ComAffix from "@/components/ComAffix.vue";
import {ref, computed, watch, onMounted,onUnmounted} from 'vue';
import router from '@/router/index.js'
import {searchTagByNew, searchTagInfo, subscribeTag} from "@/api/search.js";
import {humanizeNumberByWang} from "@/utiles/format.js";
import {checkLogin} from "@/utiles/route.js";
import {useUserStore} from "@/stores/index.js";
const userStore = useUserStore()
const route = computed(() => router.currentRoute.value);
const tagName = route.value.query.tagName
console.log("tagName:"+tagName)
// 模拟文章数据
import {
  searchTagByHotWeek,
  searchTagByHotMonth,
  searchTagByHotTotal
} from '@/api/search'


const hotRankType = ref('weekly')
const sortType = ref('latest')

// API映射表
const apiMap = {
  weekly: searchTagByHotWeek,
  monthly: searchTagByHotMonth,
  total: searchTagByHotTotal
}

// 获取热门帖子
const getHotPosts = async () => {
  if (isLoading.value || !hasMore.value) return;
  isLoading.value = true;
  try {
    const res = await apiMap[hotRankType.value](route.value.query.tagName,pageNum.value,pageSize.value)
    if(posts.value.length>0){
      await sleep(1000);
    }
    if (isRefreshing.value) {
      posts.value = res.data.data;
    } else {
      posts.value = [...posts.value, ...res.data.data];
    }
    hasMore.value = res.data.data.length >= pageSize.value;
    console.log("结果："+posts.value.length+" "+hasMore.value)
    pageNum.value++;
  } finally {
    isLoading.value = false;
    isRefreshing.value = false;
    pullDistance.value = 0;
  }
}

// 监听筛选条件变化
watch([hotRankType, tagName], () => {
  if (sortType.value === 'hottest') {
    pageNum.value = 1
    hasMore.value = true
    isLoading.value = false
    posts.value = []
    getHotPosts()
  }
})

const posts = ref([
])

const sortChange = () => {
  pageNum.value = 1
  hasMore.value = true
  isLoading.value = false
  posts.value = []
  if(sortType.value==='latest'){
    loadData()
  }else{
    getHotPosts()
  }
}

const tagInfo = ref({})
const getTagInfo = async () => {
  const res = await searchTagInfo(route.value.query.tagName,userStore.user.id)
  tagInfo.value = res.data.data
}
getTagInfo()
const subscribe = async (sign) =>{
  console.log(tagInfo.value)
  if(tagInfo.value===null || !checkLogin())
    return;
  await subscribeTag(tagInfo.value.name,sign)
  await getTagInfo()
}

//分页
const pageNum= ref(1);
const pageSize = ref(4)
const hasMore = ref(true);
const isLoading = ref(false);
const isRefreshing = ref(false);
const pullDistance = ref(0);

const sleep = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms));
};
const loadData = async () => {
  if (isLoading.value || !hasMore.value) return;
  isLoading.value = true;
  try {
    const newData = await searchTagByNew(tagName,pageNum.value,pageSize.value)
    if(posts.value.length>0){
      await sleep(1000);
    }
    if (isRefreshing.value) {
      posts.value = newData.data.data;
    } else {
      posts.value = [...posts.value, ...newData.data.data];
    }
    hasMore.value = newData.data.data.length >= pageSize.value;
    console.log("结果："+posts.value.length+" "+hasMore.value)
    pageNum.value++;
  } finally {
    isLoading.value = false;
    isRefreshing.value = false;
    pullDistance.value = 0;
  }
};

onMounted(() => {
  loadData();
});
// 滚动分页处理
const handleScroll = () => {

  const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
  if (scrollTop + clientHeight >= scrollHeight - 50 && !isLoading.value) {
    if(sortType.value==='latest'){
      loadData()
    }else{
      getHotPosts()
    }
  }
};
// 在挂载时添加监听
onMounted(() => {
  window.addEventListener('scroll', handleScroll);
});

// 卸载时移除监听
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});

</script>

<template>
  <div class="main" >
    <el-affix :offset="0">
      <ComAffix></ComAffix>
    </el-affix>
    <div class="w"
         @scroll="handleScroll" >
      <!-- 导航区域 -->
      <div class="search-nav">
        <div class="nav-left">
          <span>
            <router-link  :to="{ name: 'SearchPost', query: { searchName: tagName} }">文章</router-link>
          </span>
          <span  class="active">标签</span>
          <span>
             <router-link :to="{ name: 'SearchUser', query: { nickname: tagName} }">用户</router-link>
          </span>
        </div>
      </div>

      <!-- 标签信息栏 -->
      <div class="tag-nav">
        <div class="tag-header">
          <h2>{{tagName}}</h2>
          <div class="tag-stats">
            <span>{{ tagInfo.involveCount || 0 }} 参与</span>
            <el-divider direction="vertical" />
            <span>{{humanizeNumberByWang(tagInfo.views) || 0}} 浏览</span>
          </div>
          <span v-if="tagInfo.isSubscribe===1">
            <el-button @click="subscribe(1)" type="success">已订阅</el-button>
          </span>
          <span v-else>
            <el-button @click="subscribe(0)" type="primary">订阅</el-button>
          </span>
        </div>
      </div>

      <!-- 排序栏 -->
      <div class="sort-bar">
        <div class="sort-options">
          <el-radio-group v-model="sortType" @change="sortChange">
            <el-radio-button label="latest">最新</el-radio-button>
            <el-radio-button label="hottest" >最热</el-radio-button>
          </el-radio-group>

          <div v-if="sortType === 'hottest'" class="rank-types">
            <el-radio-group v-model="hotRankType" size="small"  >
              <el-radio-button label="weekly">周榜</el-radio-button>
              <el-radio-button label="monthly">月榜</el-radio-button>
              <el-radio-button label="total">总榜</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </div>

      <div class="post-list" :style="{ transform: `translateY(${isRefreshing ? 80 : 0}px)` }">
        <div
          v-for="post in posts"
          :key="post.id"
          class="post-item"
        >
          <!-- 内容区域 -->
          <div class="content">
            <span class="title" v-html="post.title"></span>
            <p class="preview" v-html="post.content"></p>

            <!-- 标签 -->
            <div class="tags">
              <el-tag
                v-for="tag in post.tags"
                :key="tag"
                size="small"
                type="info"
              >{{ tag }}
              </el-tag>
            </div>

            <!-- 作者信息 -->
            <div class="author-info">
              <el-avatar
                :size="32"
                :src="post.author.avatar"
              />
              <div class="meta">
                <span class="name">{{ post.author.nickname }}</span>
                <span class="time">{{ post.createTime }}</span>
                <span class="info">热度({{post.heat}})</span>
                <span class="info">点赞({{post.likeCount}})</span>
                <span class="info">收藏({{post.collectCount}})</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="isLoading" class="loading">加载中...</div>
      <div v-if="!hasMore" class="no-more">没有更多数据了</div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.main {
  min-height: 100vh;
  background-color: #f6f3f3;
}

.w {
  width: 1000px;
  margin: 0 auto;
  overflow-y: auto;
  /* 隐藏滚动条（Chrome/Safari/Edge） */
  &::-webkit-scrollbar {
    width: 0;
    background: transparent;
  }
}

.search-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 30px 0 ;
  padding: 20px 20px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);

  .nav-left {
    span {
      margin-right: 30px;
      cursor: pointer;
      color: #666;
      padding: 8px 12px;
      border-radius: 4px;

      &.active {
        background: #f0f2f5;
        color: #409eff;
        font-weight: 500;
      }

      &:hover {
        background: #f5f7fa;
      }
    }
  }

  .active {
    background: #f0f2f5;
    color: #409eff;
    font-weight: 500;
  }
  a {
    text-decoration: none;
    cursor: pointer;
    color: #636363;
  }
}

.tag-nav {
  background: white;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);

  .tag-header {
    h2 {
      margin: 0 0 10px;
      color: #333;
      font-size: 24px;
    }

    .tag-stats {
      display: flex;
      align-items: center;
      gap: 12px;
      color: #666;

    }
  }
}

.sort-bar {
  margin-bottom: 20px;
  background: white;
  padding: 16px;
  border-radius: 4px;

  .sort-options {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .rank-types {
      margin-left: 20px;
    }
  }
}


.post-list {
  display: flex;
  align-items: normal;
  flex-wrap: wrap;
  gap: 37px;
}

.post-item {
  display: inline-block;
  background-color: white;
  height: 230px;
  width: 430px;
  padding: 20px;
  margin-bottom: 10px;

  .content {

    .title {
      margin: 0 0 12px;
      font-size: 18px;
      color: #333;
      font-weight: bold;
      max-width: 450px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      display: inline-block;
    }

    .preview {
      margin: 0 0 10px;
      color: #666;
      font-size: 15px;
      line-height: 1.5;
      height: 115px;
      display: inline-block;
      overflow: hidden;
      text-overflow: ellipsis;
      font-family: 'serif','微软雅黑';

    }

    .preview > * {
      display: inline;   /* 块级标签转为行内 */
      margin: 0;         /* 清除默认外边距 */
    }

    :deep(.preview) img {
      height: 118px;
    }

    .tags {
      padding-bottom: 8px;
      margin-bottom: 3px;
      width: 440px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      display: inline-block;
      border-bottom: 1px solid #cdcbcb;

      .el-tag {
        margin-right: 8px;
      }
    }

    .author-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .meta {
        display: flex;
        gap: 5px;
        .name {
          color: #333;
          font-size: 14px;
          width: 100px;
          display: inline-block;
          overflow: hidden;
          text-overflow: ellipsis;
          font-family: 'serif', '微软雅黑';
        }

        .time {
          color: #999;
          font-size: 13px;
        }

        .info{
          font-size: 13px;
          color: #999;
        }
      }
    }
  }
}

.loading, .no-more {
  padding: 30px;
  text-align: center;
  color: #999;
}
</style>
